<template>
  <div class="manager-container">
    <!-- 搜索条件开始-->
    <el-row :gutter="20">
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                v-model="queryParams.deptName"
                placeholder="请输入部门名称"
                clearable
                size="default"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="部门状态" clearable size="default">
                <el-option label="正常" value="0">正常</el-option>
                <el-option label="停用" value="1">停用</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="default" @click="handleQuery">
              <i class="iconfont icon-chaxun">查询</i>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="default" @click="resetQuery">
              <i class="iconfont icon-chongzhi">重置</i>
            </el-button>
          </el-col>
        </el-form>
      </el-col>
        <el-col :span="4">
            <!-- 工具条开始 -->
            <el-row :gutter="20" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  size="default"
                  @click="handleAdd"
                  v-if="permissiones(['system:dept:add'])"
                >
                  <i class="iconfont icon-tianjia">新增</i>
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button style="width: 110px" type="info" plain size="default" @click="toggleExpandAll">
                  <i class="iconfont icon-paixu">展开/折叠</i>
                </el-button>
              </el-col>
            </el-row>
        </el-col>
    </el-row>
    <!-- 搜索条件结束 -->
    <!-- 工具条结束 -->

    <!-- 主页面开始 -->
    <el-table
      :header-cell-style="{background:'#fafafa'}"
      :border="true"
      v-loading="loading"
      v-if="refreshTable"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      height="600"
    >
      <el-table-column prop="deptName" label="部门名称" align="center"></el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'danger' : 'success'">
            {{
            scope.row.status == 1 ? "停用" : "正常"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button
            size="default"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="permissiones(['system:dept:edit'])"
          >编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button
            plain
            size="default"
            type="text"
            @click="handleAdd(scope.row)"
            v-if="permissiones(['system:dept:add'])"
          >新增</el-button>
          <el-divider direction="vertical" v-if="scope.row.parentId != 0"></el-divider>
          <el-button
            plain
            v-if="scope.row.parentId != 0"
            size="default"
            type="text"
            @click="handleDelete(scope.row)"
            v-show="permissiones(['system:dept:remove'])"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 主页面结束 -->
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级部门" prop="parentId">
               <tree-select
                  v-if="open"
                  v-model="form.parentId"
                  :value="form.parentId"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="选择上级部门"
                  @updateValue="updateValue"
                  :objMap="{
                    value: 'deptId',
                    label: 'deptName',
                    children: 'children',
                }"
                />
              <!-- <tree-select
                :value="form.parentId"
                v-model="form.parentId"
                :options="deptOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级部门"
                :objMap="{
                    value: 'deptId',
                    label: 'deptName',
                    children: 'children',
                }"
              /> -->
               <!-- <tree-select v-model="form.parentId" :value="form.parentId" :objMap="{
                    value: 'deptId',
                    label: 'deptName',
                    children: 'children',
                }" :show-count="true" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
//引入消息弹出框
import { ElMessageBox, ElMessage } from "element-plus";
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild
} from "@/api/system/dept";
import { handleTree } from "@/utils";
import { hasPermi } from "@/utils/auth";
//引入公共组件
import TreeSelect from "@/components/TreeSelect/index.vue"; //下拉树
import "vue3-treeselect/dist/vue3-treeselect.css";
export default {
  name: "Dept",
  components: { TreeSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: "",
        status: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: false, message: "上级部门不能为空", trigger: "change" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    updateValue(node){
      this.form.parentId = node.parentId
    },
    /**权限问题 */
    permissiones(value) {
      return hasPermi(value);
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = handleTree(response.data, "deptId");
        this.loading = false;
      }).catch(err=>{
        this.$message.error(err.msg)
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      // this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 新增按钮操作 */
    async handleAdd(row) {
      this.reset();
      await this.getTreeselect();
      if (row != null && row.deptId) {
        this.form.parentId = row.deptId;
      } else {
         this.form.parentId =0;
      }
      this.open = true;
      this.title = "添加部门";
    },
    /** 查询部门下拉树结构 */
   async getTreeselect() {
    await listDept().then(response => {
        this.deptOptions = [];
        const dept = {
          deptId: 0,
          deptName: "主类目",
          children: []
        };
        dept.children = handleTree(response.data, "deptId");
        this.deptOptions.push(dept);
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await this.getTreeselect();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch((err) => {
              this.$message.error(err.msg);
            });
          } else {
            addDept(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            }).catch((err) => {
              this.$message.error(err.msg);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.deptName + '"的数据项？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delDept(row.deptId);
        })
        .then(() => {
          this.getList();
          //弹出提示
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    }
  }
};
</script>
<style lang="less" scoped>
</style>
